from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from course.models import CourseModel
from course.ser import CourseSer
from home import models
from home.ser import NavSer, BannerSer, CategorySer


# Create your views here.
class TopNav(APIView):
    def get(self, request):
        topnav=models.NavModel.objects.filter(is_del=False,position=True).order_by('order')
        ser=NavSer(topnav,many=True)
        return Response({'msg':'ok','code':200,'data':ser.data})

class FootNav(APIView):
    def get(self, request):
        footnav=models.NavModel.objects.filter(is_del=False,position=False).order_by('order')
        ser=NavSer(footnav,many=True)
        return Response({'msg':'ok','code':200,'data':ser.data})

class Banner(APIView):
    def get(self, request):
        banner=models.BannerModel.objects.filter(is_del=False).order_by('order')
        ser=BannerSer(banner,many=True)
        return Response({'msg':'ok','code':200,'data':ser.data})

class Category(APIView):
    def get(self, request):
        category=models.CategoryModel.objects.filter(is_del=False,parent=None).order_by('order')
        ser=CategorySer(category,many=True)
        for i in ser.data:
            i['children']=i['children'][:3]
        return Response({'msg':'ok','code':200,'data':ser.data})

class Nowcate(APIView):
    def get(self, request):
        #拿到结果集
        nowcate=models.CategoryModel.objects.filter(is_del=False,id=request.query_params.get('id')).first()
        #序列化器
        ser=CategorySer(nowcate)
        # 根据一级id拿到二级id   [1,2,3,4]  然后用in操作符拿到对应的课程信息
        allcate=models.CategoryModel.objects.filter(is_del=False,parent=request.query_params.get('id'))
        catelist=[]
        for i in allcate:
            catelist.append(i.id)
        allcorse=CourseModel.objects.filter(is_del=False,category__in=catelist,ishome=True).order_by('order')
        ser2=CourseSer(allcorse,many=True)
        mydate=ser.data
        mydate['course']=ser2.data[:4]
        return Response({'msg': 'ok', 'code': 200, 'data': mydate})